package com.yuwubao.uav.tool.service.impl;

import com.github.pagehelper.Page;
import com.yuwubao.framework.bean.JsonResult;
import com.yuwubao.framework.bean.PageData;
import com.yuwubao.framework.loginFilter.TokenUtils;
import com.yuwubao.uav.tool.mapper.FrontMapper;
import com.yuwubao.uav.tool.mapper.UserMapper;
import com.yuwubao.uav.tool.service.UserService;
import com.yuwubao.uav.tool.util.StringUtil;
import com.yuwubao.uav.tool.util.sendmsg.SendCode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LogManager.getLogger(UserServiceImpl.class.getName());

    @Resource
    private UserMapper userMapper;

    @Override
    public void addZhuanfaIntegration(PageData pageData) throws Exception {
        try{
            pageData.put("sType","zhuanfa_integration");
            pageData.put("integration",userMapper.getPublishIntegration(pageData));

            pageData.put("title","转发内容积分");
            userMapper.addUserPublishIntegration(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

    }
    @Override
    public void checkUserPublish(PageData pageData, String checkResult) throws Exception {
        try{
            userMapper.checkUserPublish(pageData);
            if ("1".equals(checkResult)) {
                //增加用户积分
                pageData.put("sType","publish_integration");
                pageData.put("integration",userMapper.getPublishIntegration(pageData));

                pageData.put("title","发布内容积分");
                userMapper.addUserPublishIntegration(pageData);
            }

        }catch (Exception e) {
            logger.debug("",e);
        }

    }
    @Override
    public void addUserPublish(PageData pageData) throws Exception {
        try{

            userMapper.addUserPublish(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

    }
    @Override
    public void deleteUserBrowsingHistoryType(PageData pageData) throws Exception {
        try{

            userMapper.deleteUserBrowsingHistoryType(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

    }
    @Override
    public void addUserBrowsingHistoryType(PageData pageData) throws Exception {
        try{

            userMapper.addUserBrowsingHistoryType(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

    }
    @Override
    public void updateUserBrowsingHistoryTypeName(PageData pageData) throws Exception {
        try{

            userMapper.updateUserBrowsingHistoryTypeName(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

    }
    @Override
    public void updateUserBrowsingHistoryType(PageData pageData) throws Exception {
        try{

            userMapper.updateUserBrowsingHistoryType(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

    }
    @Override
    public int getAdviceEnrollCount(PageData pageData) throws Exception {
        try{

            return userMapper.getAdviceEnrollCount(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }
        return 0;

    }
    @Override
    public void userAdviceEnroll(PageData pageData) throws Exception {
        try{

            userMapper.userAdviceEnroll(pageData);

            //报名积分
            pageData.put("title","报名积分");
            pageData.put("sType","enroll_integration");
            pageData.put("integration",userMapper.getPublishIntegration(pageData));
            userMapper.addUserPublishIntegration(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

    }
    @Override
    public List<PageData> listUserBrowsingTypeHistory(PageData pageData) throws Exception {
        try{

            return userMapper.listUserBrowsingTypeHistory(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return null;
    }
    @Override
    public List<PageData> listUserBrowsingHistory(PageData pageData) throws Exception {
        try{

            return userMapper.listUserBrowsingHistory(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return null;
    }
    @Override
    public int listUserBrowsingHistoryCount(PageData pageData) throws Exception {
        try{

            return userMapper.listUserBrowsingHistoryCount(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return 0;
    }
    @Override
    public List<PageData> listUserPublishForAdmin(PageData pageData) throws Exception {
        try{

            return userMapper.listUserPublishForAdmin(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return null;
    }
    @Override
    public int listUserPublishForAdminCount(PageData pageData) throws Exception {
        try{

            return userMapper.listUserPublishForAdminCount(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return 0;
    }
    @Override
    public List<PageData> listMyPublish(PageData pageData) throws Exception {
        try{

            return userMapper.listMyPublish(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return null;
    }
    @Override
    public int listMyPublishCount(PageData pageData) throws Exception {
        try{

            return userMapper.listMyPublishCount(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return 0;
    }
    @Override
    public List<PageData> listUserCollection(PageData pageData) throws Exception {
        try{

            return userMapper.listUserCollection(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return null;
    }
    @Override
    public int listUserCollectionCount(PageData pageData) throws Exception {
        try{

            return userMapper.listUserCollectionCount(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return 0;
    }
    @Override
    public List<PageData> listUserIntegration(PageData pageData) throws Exception {
        try{

            return userMapper.listUserIntegration(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return null;
    }
    @Override
    public int listUserIntegrationCount(PageData pageData) throws Exception {
        try{

            return userMapper.listUserIntegrationCount(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return 0;
    }
    @Override
    public int getUserIntegrationCount(PageData pageData) throws Exception {
        try{

            return userMapper.getUserIntegrationCount(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return 0;
    }
    @Override
    public List<PageData> listUserPublish(PageData pageData) throws Exception {
        try{

            return userMapper.listUserPublish(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return null;
    }
    @Override
    public int listUserPublishCount(PageData pageData) throws Exception {
        try{

            return userMapper.listUserPublishCount(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return 0;
    }
    @Override
    public void deleteUserBrowsingHistory(PageData pageData) throws Exception {
        try{

            userMapper.deleteUserBrowsingHistory(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

    }
    @Override
    public PageData getUserBrowsingHistory(PageData pageData) throws Exception {
        try{

            return userMapper.getUserBrowsingHistory(pageData);

        }catch (Exception e) {
            logger.debug("",e);
        }

        return null;
    }

    @Override
    public boolean checkRoleIsUsing(PageData pageData) throws Exception {
        try{

            if (userMapper.checkRoleIsUsing(pageData) > 0) {
                return false;
            }

        }catch (Exception e) {
            logger.debug("",e);
        }

        return true;
    }
    @Override
    public List<PageData> listUserPrivilege(PageData pageData) throws Exception {
        try{

            return userMapper.listUserPrivilege(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }

        return null;
    }
    @Override
    public List<PageData> listFrontUserRole(PageData pageData) throws Exception {
        try{

            return userMapper.listFrontUserRole(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }

        return null;
    }

    @Transactional
    @Override
    public void addPrivilegeToRole(PageData pageData) throws Exception {
        try{
            String privilegeId = pageData.get("privilegeId") == null ? "" :pageData.getString("privilegeId");

            if (StringUtil.isNotNvlOrBlank(privilegeId)) {

                String[] ss = privilegeId.split(",");

                if (ss != null && ss.length>0) {

                    userMapper.deleteRolePrivilege(pageData);

                    for (String s : ss) {
                        pageData.put("privilegeId",s);
                        userMapper.addRolePrivilege(pageData);
                    }
                }

            }

        }catch (Exception e) {
            logger.debug("",e);
        }
    }

    @Override
    public void deleteRole(PageData pageData) throws Exception {
        try{
                userMapper.deleteRole(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
    }
    @Override
    public void updateRole(PageData pageData) throws Exception {
        try{
                userMapper.updateRole(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
    }
    @Override
    public void addRole(PageData pageData) throws Exception {
        try{
                userMapper.addRole(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
    }

    @Override
    public List<PageData> listRole(PageData pageData) throws Exception {
        try{
            List<PageData> list =userMapper.listRole(pageData);
            if (list != null && list.size()>0) {
                for (PageData pd : list) {
                    pd.put("privilege_list",userMapper.listPrivilegeForRole(pd));
                }
            }
            return list;
        }catch (Exception e) {
            logger.debug("",e);
        }
        return null;
    }
    @Override
    public int listRoleCount(PageData pageData) throws Exception {
        try{
            return userMapper.listRoleCount(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
        return 0;
    }
    @Override
    public List<PageData> listOrganization(PageData pageData) throws Exception {
        try{
            return userMapper.listOrganization(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
        return null;
    }
    @Override
    public int listOrganizationCount(PageData pageData) throws Exception {
        try{
            return userMapper.listOrganizationCount(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
        return 0;
    }

    @Transactional
    @Override
    public void deletePrivilege(PageData pageData) throws Exception {
        try{
            userMapper.deletePrivilege(pageData);
            userMapper.deleteRolePrivilegeRelation(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
    }
    @Override
    public void updatePrivilege(PageData pageData) throws Exception {
        try{
                userMapper.updatePrivilege(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
    }
    @Override
    public void addPrivilege(PageData pageData) throws Exception {
        try{
                userMapper.addPrivilege(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
    }

    @Override
    public List<PageData> listPrivilege(PageData pageData) throws Exception {
        try{
            return userMapper.listPrivilege(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
        return null;
    }
    @Override
    public int listPrivilegeCount(PageData pageData) throws Exception {
        try{
            return userMapper.listPrivilegeCount(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
        return 0;
    }


    @Transactional
    @Override
    public void updateBackendUser(PageData pageData) throws Exception {
        try{
            String userPwd = pageData.get("userPwd") == null ? "" :pageData.getString("userPwd");
            String roleId = pageData.get("roleId") == null ? "" :pageData.getString("roleId");

            if (StringUtil.isNotNvlOrBlank(userPwd)) {
                userMapper.updateUserPwd(pageData);
            }

            if (StringUtil.isNotNvlOrBlank(roleId)) {
                userMapper.deleteUserRole(pageData);
                userMapper.addUserRole(pageData);
            }

        }catch (Exception e) {
            logger.debug("",e);
        }
    }
    @Override
    public PageData login(PageData pageData) throws Exception {
        PageData rePd = new PageData();
        try{

            int userId = userMapper.userLogin(pageData);

            if (userId > 0) {
                rePd.put("token",TokenUtils.createJwtToken(String.valueOf(userId)));

                pageData.put("userId",userId);

                rePd.put("userPrivilegeList",userMapper.listUserPrivilege(pageData));
                rePd.put("userInfo",userMapper.getUserInfo(pageData));
                rePd.put("userRoleList",userMapper.listUserRole(pageData));
            }


        }catch (Exception e) {
            logger.debug("",e);
        }
        return rePd;
    }

    @Override
    public void disableOrEnableUser(PageData pageData) throws Exception {
        try{
            userMapper.disableOrEnableUser(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
    }
    @Transactional
    @Override
    public void deleteUser(PageData pageData) throws Exception {
        try{
            //2,删除用户与研究领域的关系
            userMapper.deleteUserResearchField(pageData);
            //3,删除用户与角色的关系
            userMapper.deleteUserRole(pageData);
            //4,删除用户
            userMapper.deleteUser(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
    }
    @Override
    public List<PageData> listFrontUser(PageData pageData) throws Exception {
        try{
            return userMapper.listFrontUser(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
        return null;
    }
    @Override
    public int listFrontUserCount(PageData pageData) throws Exception {
        try{
            return userMapper.listFrontUserCount(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
        return 0;
    }
    @Override
    public List<PageData> listBackendUser(PageData pageData) throws Exception {
        try{
            return userMapper.listBackendUser(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
        return null;
    }
    @Override
    public int listBackendUserCount(PageData pageData) throws Exception {
        try{
            return userMapper.listBackendUserCount(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
        return 0;
    }

    @Transactional
    @Override
    public void addUser(PageData pageData) throws Exception {
        try{

            userMapper.addUser(pageData);

            userMapper.addUserRole(pageData);

            String researchFieldIds = pageData.get("researchFieldIds") == null ? "" : pageData.getString("researchFieldIds");

            if (StringUtil.isNotNvlOrBlank(researchFieldIds)) {
                String[] rfArr = researchFieldIds.split(",");
                if (rfArr != null && rfArr.length>0) {
                    for (String s : rfArr) {
                        pageData.put("rfId",s);
                        userMapper.addUserResearchField(pageData);
                    }
                }
            }

        }catch (Exception e) {
            logger.debug("",e);
        }
    }


    @Override
    public int getUserByUserName(PageData pageData) throws Exception {
        try{
            return userMapper.getUserByUserName(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
        return 0;
    }
    @Override
    public int getUserByMail(PageData pageData) throws Exception {
        try{
            return userMapper.getUserByMail(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
        return 0;
    }
    @Override
    public int findByUserName(String userId) throws Exception {
        try{
            return userMapper.findByUserName(userId);
        }catch (Exception e) {
            logger.debug("",e);
        }
        return 0;
    }
    @Override
    public String getUserPwdById(PageData pageData) throws Exception {
        try{
            return userMapper.getUserPwdById(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
        return null;
    }
    @Override
    public void changePwd(PageData pageData) throws Exception {
        try{
            userMapper.changePwd(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }
    }
    @Override
    public JsonResult importUserList(MultipartFile fileName, HttpServletRequest request) throws Exception {

        JsonResult jsonResult = new JsonResult();
        jsonResult.setSuccessful();
        try{
            if (fileName != null) {

                // 原始名称
                String originalFilename = fileName.getOriginalFilename();

                if (!StringUtil.isNotNvlOrBlank(originalFilename)) {
                    jsonResult.setMessage("导入失败，文件名不能为空！");
                    jsonResult.setCode(JsonResult.FAILURE_CODE);
                    return jsonResult;
                } else {
                    String houzui = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                    if (!StringUtil.isNotNvlOrBlank(houzui) || !"xlsx".equals(houzui)) {
                        jsonResult = new JsonResult();
                        jsonResult.setMessage("导入失败，文件类型不正确！");
                        jsonResult.setCode(JsonResult.FAILURE_CODE);
                        return jsonResult;
                    }
                }

                // 存储图片的物理路径
                String tomcatPath = request.getSession().getServletContext().getRealPath("");
                String directory = new File(tomcatPath).getParent() + "/baseImportTemp/";

                File newFileD = new File(directory);
                if (newFileD != null && !newFileD.exists()) {
                    newFileD.mkdirs();
                }

                String wholeFileName = directory + originalFilename;
                File newFile = new File(wholeFileName);
                fileName.transferTo(newFile);

                InputStream is = new FileInputStream(newFile);
                XSSFWorkbook hWorkbook = new XSSFWorkbook(is);
                XSSFSheet hSheet = hWorkbook.getSheetAt(0);
                XSSFRow hRow;
                PageData su = null;
                String cName = null;
                String dName = null;
                String uName = null;
                String uTel = null;

                if (null != hSheet) {

                    for (int i = 1; i < hSheet.getPhysicalNumberOfRows(); i++) {
                        su = new PageData();
                        hRow = hSheet.getRow(i);
                        if (hRow != null) {
                            try {
                                //单位名称
                                cName = hRow.getCell(0) == null ? null : hRow.getCell(0).toString();

                                //部门名称
                                dName = hRow.getCell(1) == null ? null : hRow.getCell(1).toString();

                                //姓名
                                uName = hRow.getCell(2) == null ? null : hRow.getCell(2).toString();

                                //电话号码
                                uTel = hRow.getCell(3) == null ? null : getStringValueFromCell(hRow.getCell(3));

                                su.put("cName",cName);
                                su.put("dName",dName);
                                getCId(su);
                                getDId(su);
                                su.put("uName",uName);
                                su.put("uTel",uTel);

                                if (userMapper.getAddressByTel(su) < 1) {
                                    userMapper.addAddressList(su);
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }


                newFile.delete();
            }


        }catch (Exception e) {
            logger.debug("",e);
        }
        return jsonResult;
    }

    public static String getStringValueFromCell(Cell cell) {
        SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");
        DecimalFormat decimalFormat = new DecimalFormat("#.#");
        String cellValue = "";
        if(cell == null) {
            return cellValue;
        }
        else if(cell.getCellType() == Cell.CELL_TYPE_STRING) {
            cellValue = cell.getStringCellValue();
        }

        else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
            if(HSSFDateUtil.isCellDateFormatted(cell)) {
                double d = cell.getNumericCellValue();
                Date date = HSSFDateUtil.getJavaDate(d);
                cellValue = sFormat.format(date);
            }
            else {
                cellValue = decimalFormat.format((cell.getNumericCellValue()));
            }
        }
        else if(cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            cellValue = "";
        }
        else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            cellValue = String.valueOf(cell.getBooleanCellValue());
        }
        else if(cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            cellValue = "";
        }
        else if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            cellValue = cell.getCellFormula().toString();
        }
        return cellValue;
    }


    public void getCId(PageData pd) throws Exception {
        int cId = userMapper.getCId(pd);
        if (cId <= 0) {
            userMapper.addCompany(pd);
        } else {
            pd.put("cId",cId);
        }
    }
    public void getDId(PageData pageData) throws Exception {
        int dId = userMapper.getDId(pageData);
        if (dId <= 0) {
            userMapper.addDepartment(pageData);
        } else {
            pageData.put("dId",dId);
        }
    }

    @Override
    public List<PageData> listAddressListCompany() throws Exception {
        try{
            return userMapper.listAddressListCompany();
        }catch (Exception e) {
            logger.debug("",e);
        }

        return null;
    }
    @Override
    public List<PageData> listAddressListDepartment(PageData pageData) throws Exception {
        try{
            return userMapper.listAddressListDepartment(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }

        return null;
    }
    @Override
    public List<PageData> listAddressList(PageData pageData) throws Exception {
        try{
            return userMapper.listAddressList(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }

        return null;
    }

    @Resource
    private SendCode sendCode;

    @Override
    public void sendMsg(PageData pageData) throws Exception {
        try{
            sendCode.sendMsg(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }

    }
    @Override
    public void deleteAddressList(PageData pageData) throws Exception {
        try{
            userMapper.deleteAddressList(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }

    }
    @Override
    public void deleteAddressListCompany(PageData pageData) throws Exception {
        try{
            userMapper.deleteAddressListCompanyByCompanyId(pageData);
            userMapper.deleteAddressListDepartmentByCompanyId(pageData);
            userMapper.deleteCompanyAddressListByCompanyId(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }

    }
    @Override
    public void deleteAddressListDepartment(PageData pageData) throws Exception {
        try{
            userMapper.deleteAddressListDepartmentById(pageData);
            userMapper.deleteAddressListByDepartmentId(pageData);
        }catch (Exception e) {
            logger.debug("",e);
        }

    }

    @Resource
    private FrontMapper frontMapper;

    @Override
    public void addUserCollection(PageData pageData) throws Exception {
        try{
            String collectionFlag = frontMapper.getCollectionFlag(pageData);
            if (StringUtil.isNotNvlOrBlank(collectionFlag)) {
                if ("1".equals(collectionFlag)) {
                    pageData.put("isCollection","0");
                } else {
                    pageData.put("isCollection","1");
                }
                frontMapper.updateUserCollection(pageData);
            } else {
                //frontMapper.addUserCollection(pageData);
            }

        }catch (Exception e) {
            logger.debug("",e);
        }

    }


}
